package com.topisv.tms.web.work.prepkg;

import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springside.modules.web.Servlets;

import com.topisv.tms.entity.AreaGroup;
import com.topisv.tms.entity.Customers;
import com.topisv.tms.entity.work.prepkg.PrepkgPlan;
import com.topisv.tms.service.AreaGroupService;
import com.topisv.tms.service.CustomersService;
import com.topisv.tms.service.account.ShiroDbRealm.ShiroUser;
import com.topisv.tms.service.work.prepkg.PrepkgPlanService;
import com.topisv.tms.utils.JsonUtil;

/**
 * 预包装计划—control
 * @author ch
 *
 */
@Controller
@RequestMapping(value = "/prepkgPlan")
public class PrepkgPlanController {

	private static final Logger logger = LoggerFactory.getLogger(PrepkgPlanController.class);
	private static final int PAGE_SIZE = 30;

	@Autowired
	private CustomersService customersService;
	@Autowired
	private AreaGroupService areagroupService;
	@Autowired
	private PrepkgPlanService prepkgPlanService;
	
	

	/**
	 * 导向预包装计划页面
	 * @param model
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "toPrepkgPlanMgrPage")
	public String toPrepkgPlanMgrPage(Model model, ServletRequest request) {
		try {
			//查出当前用户关联的商家列表
			ShiroUser curUser = (ShiroUser) SecurityUtils.getSubject().getPrincipal();
			List<Customers> customerList=this.customersService.loadCustomerByAuthority(curUser);
			model.addAttribute("customerList",customerList);
			model.addAttribute("userType",curUser.userType);
			
			//如果是paiu用户,初始化数据
			if("paiu".equals(curUser.userType)){
			    //查询出库单
				Map<String, Object> param =new HashMap<String, Object>();
				param.put("customerCodes", StringUtils.isBlank(curUser.customers)?"blank":curUser.customers);
				Page<PrepkgPlan> page =this.prepkgPlanService.loadByParam(param,1, PAGE_SIZE);
				model.addAttribute("page", page);
			}
			
			
			//如果是商家用户,初始化数据
			if("customer".equals(curUser.userType)){
				String customerCode=curUser.customerCode;
				model.addAttribute("customerCode", customerCode); 
				
				//初始化仓库数据
				List<AreaGroup> warehouseList=this.areagroupService.loadAreaGroupByAuthority(curUser,customerCode);
				model.addAttribute("warehouseList", warehouseList);
				
				//查询出库单
				Map<String, Object> param =new HashMap<String, Object>();
				param.put("customerCodes", customerCode);
				Page<PrepkgPlan> page =this.prepkgPlanService.loadByParam(param,1, PAGE_SIZE);
				model.addAttribute("page", page);
			}
			
		} catch (Exception e) {
			logger.error("error",e);
		}
		return "work/prepkg/prepkgPlanMgr";
	}
	
	
	/**
	 * 查询计划
	 * @param model
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "queryPlan")
	public String queryPlan(Model model, ServletRequest request) {
		try {
			
			//查出当前用户关联的商家列表
			ShiroUser curUser = (ShiroUser) SecurityUtils.getSubject().getPrincipal();
			List<Customers> customerList=this.customersService.loadCustomerByAuthority(curUser);
			model.addAttribute("customerList",customerList);
			model.addAttribute("userType",curUser.userType);
			
			//查询出库单
			Map<String, Object> param = Servlets.getParametersStartingWith(request, "_");
			
			String fromDateStr=(String) param.get("fromDate");
			String toDateStr=(String) param.get("toDate");
			Date fromDate=null;
			Date toDate=null;
			SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			if(StringUtils.isNotEmpty(fromDateStr)){
				fromDate=sdf.parse(fromDateStr+" 00:00:00");
			}
			if(StringUtils.isNotEmpty(toDateStr)){
				toDate=sdf.parse(toDateStr+" 23:59:59");
			}
			param.put("fromDate", fromDate);
			param.put("toDate", toDate);
			
			
			Page<PrepkgPlan> page =this.prepkgPlanService.loadByParam(param,1, PAGE_SIZE);
			model.addAttribute("page", page);
			model.addAttribute("param", param);
			
			//初始化仓库数据
			String customerCode=(String) param.get("customerCode");
			if(customerCode!=null){
			   List<AreaGroup> warehouseList=this.areagroupService.loadAreaGroupByAuthority(curUser, customerCode);
			   model.addAttribute("warehouseList", warehouseList); 
			}
			  
		} catch (Exception e) {
			
			logger.error("error",e);
		}
		return "work/prepkg/prepkgPlanMgr";
	}
	
	/**
	 * 导向创建预包装计划页面
	 * @param model
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "toCreatePlan")
	public String toCreatePlan(Model model, ServletRequest request) {
		try {
			
			//查出当前用户关联的商家列表
			ShiroUser curUser = (ShiroUser) SecurityUtils.getSubject().getPrincipal();
			List<Customers> customerList=this.customersService.loadCustomerByAuthority(curUser);
			model.addAttribute("customerList",customerList);
			model.addAttribute("userType",curUser.userType);
			
			//如果是商家用户,初始化数据
			if("customer".equals(curUser.userType)){
				String customerCode=curUser.customerCode;
				model.addAttribute("customerCode", customerCode); 
				
				//初始化仓库数据
				List<AreaGroup> warehouseList=this.areagroupService.loadAreaGroupByAuthority(curUser,customerCode);
				model.addAttribute("warehouseList", warehouseList);
				
			}
			
		} catch (Exception e) {
			logger.error("error",e);
		}
		return "work/prepkg/prepkgPlanCreate";
	}
	
	/**
	 * 创建计划
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "ajaxCreatePlan")
	@SuppressWarnings("unchecked")
	public void ajaxCreatePlan(ServletRequest request,HttpServletResponse response) {
		try {	
			
			String customerCode=request.getParameter("customerCode"); 
			String warehouseCode=request.getParameter("warehouseCode"); 
			
			String jsonText=request.getParameter("jsonText");
			JSONArray infoArray = JSONArray.fromObject(jsonText);
			
			Map<String, Integer> infoMap=new HashMap<String, Integer>();
			for (Object info : infoArray) {
				Map<String, Object> map=(Map<String, Object>)info;
				String sku=(String)map.get("sku");
				Integer num=Integer.valueOf(map.get("num")+"");
				infoMap.put(sku, num);
			}
			
			String result=this.prepkgPlanService.createPlan(customerCode,warehouseCode,infoMap);
			
			Map<String, Object> map=new HashMap<String, Object>();
			map.put("result", result);
			String json = JsonUtil.getObjectString(map);
			PrintWriter out;
			out = response.getWriter();
			out.print(json);
			
		} catch (Exception e) {
			
			logger.error("error",e);
		}
	}
	
}
